#include "workCmd.h"

/* su 到root用户，
   不然会(权限不足)getspnam: Permission denied */
void get_salt(char *salt, char *passwd)
{
    int i, j;
    printf("check: ");
    for (i = 0, j = 0; passwd[i] && j < 4; ++i)
    {
        if (passwd[i] == '$'){
            ++j;
        }
    }
    int len = i;
    if(j == 4){
        --len;
    }
    strncpy(salt, passwd,len); // 取出盐值部分
    salt[len] = '\0';
}

int login(client_t *pclient)
{
    struct spwd *sp;

    char passwd[20] = {0};
    char salt[512] = {0};
    int datalength;
    train_t train;

    /* printf("%s\n",pclient->userName); */
    //通过读取用户名获取密文信息
    sp = getspnam(pclient->userName);
    ERROR_CHECK(sp, NULL, "getspnam");

    //通过crypt函数对密码进行加密得到密文
    get_salt(salt, sp->sp_pwdp);

    /* printf("salt = %s\n", salt); */
    while (1)
    {
        //接收密码
        bzero(passwd, sizeof(passwd));
        recvn(pclient->fd, &datalength, sizeof(int));
        recvn(pclient->fd, passwd, datalength);
        /* printf("passwd = %s sp = %s crypt = %s\n",passwd,sp->sp_pwdp,crypt(passwd,salt)); */

        //匹配密码
        if (strcmp(sp->sp_pwdp, crypt(passwd, salt)) == 0)
        {
            //密码正确
            strcpy(train.data,"OK");
            train.length = strlen(train.data);
            send(pclient->fd,&train.length,sizeof(train.length),MSG_NOSIGNAL);
            send(pclient->fd,train.data,train.length,MSG_NOSIGNAL);
            printf("Passwd is %s!\n",train.data);
            break;
        }
        strcpy(train.data,"WRONG");
        train.length = strlen(train.data);
        send(pclient->fd,&train.length,sizeof(train.length),MSG_NOSIGNAL);
        send(pclient->fd,train.data,train.length,MSG_NOSIGNAL);
        printf("Passwd is %s!\n",train.data);
    }
    // 设置基目录为实际路径
    char base[1024];
    getcwd(base, sizeof(base));
    strcpy(pclient->baseDir, base);
    strcat(pclient->baseDir, "/");
    strcat(pclient->baseDir, pclient->userName);
    
    if(access(pclient->baseDir,F_OK) == -1){
        mkdir(pclient->baseDir,0755);
    }

    //设置虚拟根路径为"/"
    strcpy(pclient->pwd,"/");

    bzero(&train,sizeof(train));
    train.length = strlen(pclient->pwd);
    memcpy(train.data, pclient->pwd, train.length);
    send(pclient->fd, &train.length, sizeof(train.length), MSG_NOSIGNAL);
    send(pclient->fd, train.data, train.length, MSG_NOSIGNAL);
    printf("%s root:%s\n",pclient->userName,pclient->pwd);
    
    return 0;
}
